import { defineStore } from 'pinia'
import { getMyInfo } from '@/apis/user'
import { UserInfor } from '@/apis/user/types'
import { Local } from '@/assets/utils/storage'
import { isEmpty } from '@/assets/utils/typeofs'
const local = new Local()

const state = () => {
    return {
        token: '' as string,
        myInfo: {} as UserInfor | any
    }
}

export const userStore = defineStore('user', {
    state,
    getters: {
        useToken: (state) : string => {
            return state.token ? state.token : local.get('token')
        },
        useMyInfo: (state): UserInfor => {
            return !isEmpty(state.myInfo) ? state.myInfo : local.get('myInfo')
        }
    },
    actions: {
        setToken(token: string) {
            this.token = token
            local.add('token', token)
        },
        setMyInfo<T extends UserInfor>(data: T): void {
            Object.assign(this.myInfo, data)
            local.add('myInfo', data)
        },
        async getMyInfo(): Promise<UserInfor | any> {
            if(!this.useToken) return
            const res = await getMyInfo()
            this.setMyInfo(res.data)
            return res.data
        },
        clearLogin() {
            this.token = ''
            this.myInfo = {}
            local.remove('token')
            local.remove('myInfo')
        }
    }
})